import React, { Component } from 'react'
import PropTypes from 'prop-types'

const types = {
    a: PropTypes.number,
    b: PropTypes.string.isRequired,
    addFunc: PropTypes.func
}

function ChildA(props, context) {
    return (
        <div>
            <h1>ChildA {context.a}  {context.b}</h1>
            <ChildB />
        </div>
    )
}

ChildA.contextTypes = types

class ChildB extends Component {

    /**
     * 声明需要使用哪些上下文中的数据
     */
    static contextTypes = types


    constructor(props, context) {
        super(props, context);  // 将参数的上下文交给父类处理
        console.log(this.context);
    }

    handleChange = () => {
        this.context.addFunc(123)
    }

    render() {
        return <h2>
            ChildB，来自于上下文的数据：{this.context.a + "--" + this.context.b}
            <button onClick={this.handleChange}>更改父组件的数据</button>
        </h2>
    }
}


class ChildC extends Component {

    static contextTypes = types

    static childContextTypes = {
        a: PropTypes.number,
        c: PropTypes.string
    }

    getChildContext = () => {
        return {
            a: 1111,
            c: 'happy'
        }
    }

    render() {
        return <div>
            <h1>ChildC---{this.context.a}---{this.context.b}---{this.context.c}</h1>
            <ChildB />
        </div>
    }
}

export default class OldContextTest extends Component {

    static childContextTypes = types

    state = {
        a: 1,
        b: 'hello'
    }

    /**
     * 得到上下文中的数据
     * 
     */
    getChildContext() {
        // console.log("获取上下文中的数据");
        return {
            a: this.state.a,
            b: this.state.b,
            addFunc: (val) => {
                this.setState({
                    a: !val ? this.state.a + 1 : val + 1
                })
            }
        }
    }

    handleAdd = () => {
        this.setState({
            a: this.state.a + 1
        })
    }

    render() {
        return (
            <div>
                {/* <ChildA /> */}
                <ChildC />
                <button onClick={this.handleAdd}>a加1</button>
            </div>
        )
    }
}
